﻿using System.Collections.Generic;
using Entitas;
using Script.Manager;
using UnityEngine;

/// <summary>
/// match View - Entity
/// </summary>
public sealed class AddViewSystem : ReactiveSystem<GameEntity>
{
    private readonly Contexts context;

    public AddViewSystem (Contexts context) : base (context.game)
    {
        this.context = context;
    }

    protected override ICollector<GameEntity> GetTrigger (IContext<GameEntity> context)
    {
        return context.CreateCollector (GameMatcher.CreateViewCmdComp);
    }

    protected override bool Filter (GameEntity entity)
    {
        return true;
    }

    protected override void Execute (List<GameEntity> entities)
    {
        foreach (var entity in entities)
        {
            var view = SpawnObj (entity);
            entity.AddViewComp (view);
            entity.RemoveCreateViewCmdComp ();
        }
    }

    private View SpawnObj (GameEntity entity)
    {
        var  tag = entity.createViewCmdComp.actorTag;
        View view = PoolManager.Instance.Spawn (tag);
        view.Link (context, entity);
        return view;
    }
}